package com.tedu.movie.service;

import com.tedu.movie.mapper.CategoryMapper;
import com.tedu.movie.mapper.ItemMapper;
import com.tedu.movie.pojo.Category;
import com.tedu.movie.pojo.Item;
import com.tedu.movie.pojo.ItemCategoryVO;
import com.tedu.movie.pojo.ItemExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public boolean updateItem(Item item) {
        int updateRow= itemMapper.updateByPrimaryKeySelective(item);
        if(updateRow>=1){
            return  true;
        }else{
            return false;
        }
    }

    @Override
    public boolean deleteItem(Integer id) {
        int deleteRow =itemMapper.deleteByPrimaryKey(id);
        if (deleteRow>=1){
            return true;
        }
        return false;
    }

    @Override
    public List<ItemCategoryVO> selectAll() {
        ArrayList<ItemCategoryVO> volist=new ArrayList<>();
        List<Item> list = itemMapper.selectByExample(null);
        for(Item item:list){
            Category category=categoryMapper.selectByPrimaryKey(item.getCategoryId());
            ItemCategoryVO itemCategoryVO = new ItemCategoryVO();
            itemCategoryVO.setId(item.getId());
            itemCategoryVO.setCategoryId(item.getCategoryId());
            itemCategoryVO.setName(item.getName());
            itemCategoryVO.setImage(item.getImage());
            itemCategoryVO.setPrice(item.getPrice());
            itemCategoryVO.setItemDesc(item.getItemDesc());
            itemCategoryVO.setCategoryName(category.getName());
            volist.add(itemCategoryVO);
        }
        return volist;
    }

    @Override
    public boolean insertItem(Item item) {
        int insertRow = itemMapper.insertSelective(item);
        if(insertRow>=1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Item selectById(Integer id) {
        Item item = itemMapper.selectByPrimaryKey(id);
        return item;
    }

    @Override
    public List<Item> selectByCategoryId(Integer categoryId) {
        //select * from item where category_id=1
        ItemExample itemExample = new ItemExample();
        ItemExample.Criteria criteria = itemExample.or();
        criteria.andCategoryIdEqualTo(categoryId);
        List<Item> list = itemMapper.selectByExample(itemExample);
        return list;
    }
}
